package com.lambkit.module.common;

import cn.hutool.core.util.StrUtil;
import com.lambkit.core.Lambkit;
import com.lambkit.core.config.ConfigCenter;
import com.lambkit.db.sql.Example;
import com.lambkit.db.sql.GroupBy;
import com.lambkit.module.common.row.Setting;
import com.lambkit.module.common.service.SettingService;
import com.lambkit.module.common.sql.SettingSQL;

import java.util.ArrayList;
import java.util.List;

public class SettingConfigCenter implements ConfigCenter {

	private SettingService service;

	public SettingConfigCenter() {
		service = Lambkit.get(SettingService.class);
	}

	@Override
	public String getName() {
		return "CommonSetting";
	}
	
	@Override
	public String getValue(String key) {
		return service.get(key);
	}

	@Override
	public boolean containsKey(String key) {
		String value = service.get(key);
		return StrUtil.isNotBlank(value);
	}

	@Override
	public List<String> getKeys(String prefix) {
		GroupBy groupBy = new GroupBy("setting_key", null);
		Example example = SettingSQL.of().andSettingKeyLike(prefix + "%").example().setGroupBy(groupBy).setLoadColumns("setting_key");
		List<Setting> records = service.dao().find(example);
		List<String> keyList = new ArrayList<String>();
		for(Setting record : records) {
			keyList.add(record.getSettingKey());
		}
		return keyList;
	}

	@Override
	public boolean refresh() {
		return false;
	}

	@Override
	public void setValue(String name, String key, String value) {
		if(StrUtil.isBlank(name) || getName().equals(name)) {
			service.put(key, value);
		}
	}

	@Override
	public void removeValue(String key) {
		service.remove(key);
	}
}
